package com.dhh.sky.activity;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.dao.DataBaseHelper;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SyncService extends IntentService {
    private FileManager fManager;
	private DataBaseHelper db;
    private LiveConnectClient mClient;
	private SharedPreferences sp;
	
	public SyncService() {
		super("SyncService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		sp = getSharedPreferences("sync_file", 0);
		mClient = ((SDAApplication) getApplication()).getConnectClient();
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
		fManager = new FileManager(db);
		String path =  intent.getStringExtra("path");
		String parent =  intent.getStringExtra("parent");
		Intent bIntent = new Intent("syncService");
		bIntent.putExtra("parent", parent);
		String error = null;
		Editor editor = sp.edit();
		try {
			editor.putString("sync_"+parent, "sync_"+parent).commit();
			LiveOperation operation = mClient.get(path);   
			JSONObject result = operation.getResult();
			List<SkyDriveObject> files = new ArrayList<SkyDriveObject>();
			if (result.has(JsonKeys.ERROR)) {
				error = result.getString(JsonKeys.ERROR);
			}else{
				JSONArray data = result.optJSONArray(JsonKeys.DATA);
				for (int i = 0; i < data.length(); i++) {
		            SkyDriveObject skyDriveObj = SkyDriveObject.create(data.optJSONObject(i));
		            files.add(skyDriveObj);
		        }
				fManager.update(files,parent);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			error = e.getMessage();
		}		
		
		if(error!=null){
			bIntent.putExtra("error", error);
		}
		editor.remove("sync_"+parent).commit();
		sendBroadcast(bIntent);
	}

}
